<?php

/*
 * To change this template, choose Tools | Templates
* and open the template in the editor.
*/

class HT_Model_administrator_models_seo extends Zend_Db_Table {//ten class fai viet hoa

	protected $_db;

	public function __construct() {
		$this->_name = "seo_url";
		$this->_db = Zend_Registry::get('dbMain');
		parent::init();
	}
	
	public function getAllSeoLink(){
		$sql = " SELECT * FROM seo_url WHERE date(last_updated) = date('".date('Y-m-d')."')";
		return $this->_db->fetchAll($sql);
	}
	
	public function updateData($data,$urlId){
		$url = trim($data['url']);
		if($url != '' && !$this->_checkExistsSeoUrl($url,'update',$urlId)){
			$this->update($data, "url_id=".(int)$urlId);
			return $urlId;
		}else{
			return "-1";
		}
		
	}
	
	public function addData($data){
		$url = trim($data['url']);
		if($url != '' && !$this->_checkExistsSeoUrl($url)){
			$this->insert($data);
			return $this->getMaxId();
		}else{
			return "-1";
		}
	}
	
	private function _checkExistsSeoUrl($url,$action="insert",$urlId = null){
		if($action == 'insert'){
			$sql = "SELECT COUNT(url_id) FROM seo_url WHERE url = ?";
			return  (int)$this->_db->fetchOne($sql,array($url));
		}else{
			$sql = "SELECT COUNT(url_id) FROM seo_url WHERE url = ? AND url_id <> ?";
			return  (int)$this->_db->fetchOne($sql,array($url,$urlId));
		}
	}
	
	public function getMaxId(){
		$sql = "SELECT MAX(url_id) FROM seo_url ";
		return  (int)$this->_db->fetchOne($sql);
	}
	public function getSeo($urlId,$filter = array()) {
		$sql = " SELECT * FROM seo_url WHERE url_id= ".(int)$urlId;
		return $this->_db->fetchRow($sql);
	}
	
	public function getSeoByUrl($url) {
		$sql = " SELECT * FROM seo_url WHERE url = ? LIMIT 1 ";
		return $this->_db->fetchRow($sql,array($url));
	}
	
	public function getListSeo_nb($filter = array()) {
		$sqlPlus = $this->getListSeo_sqlPlus($filter);
		$sql = "SELECT COUNT(url_id)
		FROM seo_url 
		WHERE 1=1 $sqlPlus";
		return $this->_db->fetchOne($sql);
	}
	public function getListSeo($start=0,$size = 10,$filter = array()) {
		$sqlPlus = $this->getListSeo_sqlPlus($filter);
		$sql = "SELECT *
		FROM seo_url 
		WHERE 1=1 $sqlPlus ORDER BY url LIMIT $start,$size";
		return $this->_db->fetchAll($sql);
	}
	
	private function getListSeo_sqlPlus($filter){
		$sqlPlus = null;
		$keyword = trim(@$filter['keyword']);
		if($keyword){
			$sqlPlus .= " AND url LIKE '%$keyword%' ";
		}
		return $sqlPlus;
	}
	
}

?>
